<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small"
             :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="服务名" prop="serviceName">
        <el-select
          style="width:295px;"
          v-model="queryParams.serviceId"
          clearable
          filterable
          placeholder="请选择服务名,支持搜索过滤"
          @change="val => handleStoreQueryParams(storeServiceNameKey, val)"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in serviceOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="链路ID" prop="traceId">
        <el-input v-model="queryParams.traceId" placeholder="链路ID,仅支持精确查询" clearable style="width:295px;"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="请求地址" prop="requestUri">
        <el-input v-model="queryParams.requestUri" placeholder="请求地址,支持模糊查询" clearable style="width:295px;"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="负责人" prop="chargeUserId">
        <el-select v-model="queryParams.chargeUserId" filterable clearable placeholder="负责人,选项支持模糊过滤" style="width: 295px;"
                   @change="val => handleStoreQueryParams(storeChargeUserKey, val)"
                   @keyup.enter.native="handleQuery">
          <el-option :key="self.value" :label="self.label"
                     :value="self.value"></el-option>
          <el-option v-for="user in userOptions" :key="user.userId" :label="user.name"
                     :value="user.userId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="异常标识" prop="stackHash">
        <el-input v-model="queryParams.stackHash" placeholder="异常标识,仅支持精确查询" clearable style="width:295px;"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="异常名" prop="errorName">
        <el-input v-model="queryParams.errorName" placeholder="异常名,支持模糊查询" clearable style="width:295px;"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="告警时间" prop="alarmTimes">
        <el-date-picker
          style="width:335px;"
          v-model="queryParams.alarmTimes"
          clearable
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          align="right"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          ref="alarmTimesDatePicker"
          @keyup.enter.native="handleQuery"
          @change="val => handleStoreQueryParams(storeAlarmTimesKey, val)"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="display: flex; align-items: center;">
      <div style="margin-left: auto;">
        <el-link
          style="font-size: 13px; color: blue;"
          :underline="false"
          @click="handleDoc">
          什么是告警日志？
        </el-link>
      </div>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList">
      </right-toolbar>
    </el-row>


    <el-table ref="table" v-loading="loading" :data="logList"
              @selection-change="handleSelectionChange"
              @row-contextmenu="handleRowContextMenu">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="table-expand">
            <div style="height: 250px;overflow: auto;">
              <json-viewer :value="props.row.logMessage == null ? {} :  props.row.logMessage"
                           :expand-depth=1
                           :expanded="false"
                           copyable
                           :boxed="false"></json-viewer>
            </div>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="所属服务" align="center" prop="serviceName"
                       :formatter="(row, column, cellValue, index) =>
                       `${row.serviceCnName ? row.serviceCnName:'unknown'}(${row.serviceZnName ? row.serviceZnName:'unknown'})`"
                       :show-overflow-tooltip="true" width="180"/>
      <el-table-column label="负责人" align="center" show-overflow-tooltip prop="chargeUserName"/>
      <el-table-column label="请求地址" align="center" show-overflow-tooltip prop="requestUri"/>
      <el-table-column label="告警时间" align="center" prop="alarmTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.alarmTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件位置" align="center" show-overflow-tooltip prop="errorFileName">
        <template #default="scope">
           <span style="color: #1890ff; cursor: pointer;" @click="handleCopy(scope.row.errorFileName)">
                  {{ scope.row.errorFileName }}
           </span>
        </template>
      </el-table-column>
      <el-table-column label="异常标识" align="center" prop="stackHash" width="100">
        <template #default="scope">
          <el-tooltip v-if="scope.row.stackHash" content="点击查询相似异常" placement="top">
                <span style="color: #1890ff; cursor: pointer;" @click="handleStackHashQuery(scope.row)">
                  {{ scope.row.stackHash }}
                </span>
          </el-tooltip>
          <span v-else>{{scope.row.stackHash}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['hawk-eye:log:edit']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-order"
            v-if="scope.row.isCreateProblem === 1"
            @click="handleAddProblem(scope.row)"
            v-hasPermi="['hawk-eye:problem-record:query']"
          >缺陷信息
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-right"
            v-else
            @click="handleAddProblem(scope.row)"
            v-hasPermi="['hawk-eye:problem-record:add']"
          >创建缺陷
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="Number(total)>0"
      :total="Number(total)"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <modal-form ref="modalForm"/>
    <problem-modal-form ref="problemModalForm" @submitted="getList"/>
  </div>
</template>

<script>
  import {logPageList, removeLog, addLog, updateLog} from "@/api/hawkeye/alarmlog";
  import ModalForm from "./modules/ModalForm";
  import ProblemModalForm from "@/views/hawkeye/problemrecord/modules/ModalForm";
  import SearchToolbar from "./modules/SearchToolbar";
  import {serviceNameList, userListNotSelf} from "@/api/hawkeye/service";
  import {CodeEditor} from "bin-code-editor"
  import JsonViewer from 'vue-json-viewer'
  import {formatDate} from "@/utils/index";

  export default {
    name: "AlarmLog",
    components: {
      ModalForm, ProblemModalForm, SearchToolbar, CodeEditor, JsonViewer
    },
    data() {
      return {
        top: 0,
        left: 0,
        selectedRow: {},
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 【请填写功能名称】表格数据
        logList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          alarmTimes: []
        },
        userOptions: [],
        self: {label: '仅看自己', value: -1},
        pickerOptions: {
          shortcuts: [
            {
              text: '近5分钟',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 600 * 500);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '近10分钟',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 600 * 1000);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '近一小时',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 1);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '近一天',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            }]
        },
        serviceOptions: [],
        storeAlarmTimesKey: 'hawkEye:alarmlog:alarmDatePicker',
        storeServiceNameKey: 'hawkEye:alarmlog:storeServiceNameKey',
        storeChargeUserKey: 'hawkEye:service:storeChargeUserKey',
        visible: false
      };
    },
    created() {
      let stackHash = this.$route.query.stackHash;
      if (stackHash) {
        this.$set(this.queryParams, 'stackHash', stackHash)
      }
      this.initDatePicker();
      this.getUserList();
      this.getServiceNameList();
      this.getList();
    },
    methods: {
      initDatePicker() {
        let serviceAsString = localStorage.getItem(this.storeServiceNameKey);
        if (serviceAsString) {
          try {
            this.$set(this.queryParams, 'serviceId', JSON.parse(serviceAsString))
          } catch (e) {
            localStorage.removeItem(this.storeServiceNameKey);
          }
        }
        let picker1 = localStorage.getItem(this.storeAlarmTimesKey);
        let now = new Date()
        if (picker1) {
          try {
            let times = JSON.parse(picker1);
            let diff = new Date(times[1]).getTime() - new Date(times[0]).getTime();
            this.$set(this.queryParams, 'alarmTimes', [formatDate(new Date(now.getTime() - diff)), formatDate(now)])
          } catch (e) {
            localStorage.removeItem(this.storeAlarmTimesKey);
          }
        }
        let userIdAsString = localStorage.getItem(this.storeChargeUserKey);
        if (userIdAsString) {
          try {
            this.$set(this.queryParams, 'chargeUserId', JSON.parse(userIdAsString))
          } catch (e) {
            localStorage.removeItem(this.storeChargeUserKey);
          }
        }
      },
      getServiceNameList() {
        serviceNameList().then(res => {
          this.serviceOptions = res.data;
        })
      },
      /** 查询【请填写功能名称】列表 */
      getList() {
        this.loading = true;
        logPageList(this.queryParams).then(res => {
          this.logList = res.records;
          this.total = res.total;
          this.loading = false;
        });
      },
      getUserList() {
        userListNotSelf().then(res => {
          this.userOptions = res.data;
        })
      },
      handleStoreQueryParams(key, value) {
        if (value) {
          localStorage.setItem(key, JSON.stringify(value));
        } else {
          localStorage.removeItem(key);
        }
      },
      handleStackHashQuery(row) {
        this.$set(this.queryParams, 'stackHash', row.stackHash)
        this.$modal.msgSuccess("查询" + row.stackHash + "近似异常");
        this.getList();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      // 搜索
      toggleSearch() {
        this.showSearch = !this.showSearch;
      },
      /** 重置按钮操作 */
      resetQuery() {
        localStorage.removeItem(this.storeAlarmTimesKey);
        localStorage.removeItem(this.storeServiceNameKey);
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.baseAlarmId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      handleRowContextMenu(row, column, event) {
        // 阻止默认上下文菜单
        event.preventDefault();
        // 更新菜单位置
        this.left = event.clientX;
        this.top = event.clientY;
        // 设置选中行
        this.selectedRow = row;
        // 显示菜单
        this.visible = true;
      },
      /**  */
      handleView(row) {
        this.$refs.modalForm.open(row);
      },
      /**  */
      handleAddProblem(row) {
        this.$refs.problemModalForm.createProblem(row);
      },
      handleCopy(text) {
        // 调用复制方法
        this.$clipboard(text)
          .then(() => {
            this.$modal.msgSuccess("内容已复制到剪切板,可进行粘贴");
          })
          .catch((err) => {
            this.$modal.msgError("复制失败,请确认浏览器支持复制功能");
          })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.baseAlarmId != null) {
              updateLog(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addLog(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.baseAlarmId || this.ids;
        this.$modal.confirm('是否确认删除该数据项？').then(function () {
          return removeLog(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      handleDoc(){
        let url = 'https://www.wolai.com/vHsA9FbXEmVZjBxqdjv2H4';
        if (!url) {
          return;
        }
        window.open(url);
      }
    }
  };
</script>
<style scoped="css">
  /* 隐藏 Tooltip */
  .hide-tooltip .el-tooltip__popper {
    display: none !important;
  }
</style>
